#!/usr/bin/env python
# coding: utf-8

# # 导入数据

# In[25]:


import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split,GridSearchCV,cross_val_score
from sklearn.linear_model import LogisticRegression as LR
from sklearn.preprocessing import StandardScaler
from sklearn import metrics

X = load_iris().data # 特征
Y = load_iris().target # 标签


# # 切分数据集

# In[10]:


Xtrain,Xtest,Ytrain,Ytest = train_test_split(X,Y,test_size=0.3,random_state=420)


# # 使用标准化包，对训练集来学习，从而对训练集和测试集来做标准化

# In[14]:


std = StandardScaler().fit(Xtrain)
Xtrain_ = std.transform(Xtrain)
Xtest_ = std.transform(Xtest)


# # 在确定l2范式的情况下，使用网格搜索判断solver, C的最优组合

# In[21]:


lr = LR(penalty='l2',max_iter=1000)
p = {
    'C':list(np.linspace(0.05,1,19)),
    'solver':['liblinear','sag','newton-cg','lbfgs']
}
GS = GridSearchCV(lr,p,cv=5)
GS.fit(Xtrain_,Ytrain)
GS.best_score_,GS.best_params_


# # 将最优的结果重新用来实例化模型，查看训练集和测试集下的分数

# In[24]:


lr_new = LR(penalty='l2',max_iter=1000,C=GS.best_params_['C'],solver=GS.best_params_['solver'])
lr_new.fit(Xtrain_,Ytrain)
lr_new.score(Xtrain_,Ytrain),lr_new.score(Xtest_,Ytest)


# # 计算精准率

# In[31]:


lr_new.predict(Xtest_)
score1 = metrics.precision_score(Ytrain,lr_new.predict(Xtrain_),average='micro')  #训练集
score2 = metrics.precision_score(Ytest,lr_new.predict(Xtest_),average='micro') # 测试集
score1,score2


# In[ ]:




